class TreeNode {
    public TreeNode left;
    public TreeNode right;
    public int val;

    public TreeNode(int val) {
        this.val = val;
    }
}

class Solution {
    public int postIndex = 0;// 用来遍历 后续遍历数组的

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length - 1;
        return buildTreeChild(inorder, postorder, 0, postIndex);
    }

    public TreeNode buildTreeChild(int[] inorder, int[] postorder, int ib, int ie) {
        if (ib > ie) {
            return null;
        }
        TreeNode root = new TreeNode(postorder[postIndex]);
        int rootIndex = findIndex(inorder, ib, ie, postorder[postIndex]);
        postIndex--;
        root.right = buildTreeChild(inorder, postorder, rootIndex + 1, ie);
        root.left = buildTreeChild(inorder, postorder, ib, rootIndex - 1);
        return root;
    }

    public int findIndex(int[] inorder, int ib, int ie, int key) {
        for (int i = ib; i <= ie; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}